package com.webex.ta.hydra.core;

import com.webex.ta.hydra.gui.table.celleditor.TextArea2Editor;
import com.webex.ta.hydra.gui.table.celleditor.ListEditor;
import com.webex.ta.hydra.gui.table.celleditor.HttpParamEditor;
import com.webex.ta.hydra.gui.table.celleditor.HydraDefaultTableCellEditor;

import javax.swing.table.TableCellEditor;
import javax.swing.*;


/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-8-18
 * Time: 9:27:33
 */
public abstract class AbstractKeyword implements Keyword {

    protected HydraParameter[] params;

//    public AbstractKeyword() {}

    public String getName() {
        return this.getClass().getSimpleName();
    }

    public void setParameters(HydraParameter... params) {
        this.params = params;
    }

    public HydraParameter[] getParameters() {
        return params;
    }

    public int getParameterSize() {
        if (params != null)
            return params.length;
        return 0;
    }

    public HydraParameter getParameterAt(int idx) {
        return params[idx];
    }

    public boolean validateCommand(final Command cmd) {
        boolean pass = true;
        ParamDescriptor[] descriptors = getParamDescriptors(cmd);
        if (descriptors != null && descriptors.length > 0) {
            // check each parameter against the descriptor
            for (int i = 0; i < descriptors.length; i++) {
                if (i < cmd.getParameterSize()) {
                    String param = cmd.getParameter(i);
                    if ((param == null || param.equals("")) && !descriptors[i].isOptional()) {
                        cmd.putValidationInfo(Integer.valueOf(i + 1),
                                "Parameter missing");
                        pass = false;
                    } else {
//                        cmd.removeValidationInfo(Integer.valueOf(i + 1));
                    }
                } else {
                    if (!descriptors[i].isOptional()) {
                        cmd.putValidationInfo(Integer.valueOf(i + 1),
                                "Parameter missing");
                        pass = false;
                    }
                }
            }

            if (cmd.getParameterSize() > descriptors.length) {

            }
        }
        return pass;
    }

    public TableCellEditor getParameterEditor(Command cmd, int paramIndex) {
        ParamDescriptor[] des = getParamDescriptors(cmd);
        switch (des[paramIndex].getType()) {
            case TEXTAREA:
                return new TextArea2Editor();
            case LIST:
                return new ListEditor(new JComboBox(des[paramIndex].getCandidates()));
            case HTTP:
                return new HttpParamEditor();
        }
        return new HydraDefaultTableCellEditor(new JTextField());
    }
}
